package com.example.day_blog.controller;

import com.example.day_blog.model.BlogInfo;
import com.example.day_blog.model.Comment;
import com.example.day_blog.model.Result;
import com.example.day_blog.service.BlogService;
import com.example.day_blog.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author starsea
 * @date 2024-01-18 16:27
 */
@RestController
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    private BlogService blogService;
    @RequestMapping("/getlist")

    public List<BlogInfo> getBlogList()
    {
        return blogService.getBlogList();
    }
    /**
     * 获取博客详情页面
     */
    @RequestMapping("/getBlogDetail")
    public  BlogInfo getBlogDetail(HttpServletRequest request, Integer blogId)
    {
        BlogInfo blogInfo=blogService.getBlogDetail(blogId);
        //判断作者是否为登录用户
        String token =request.getHeader("user_token");
        Integer userId=JwtUtils.getUserIdFromToken(token);
        if(userId!=null && userId==blogInfo.getUserId())
        {
            blogInfo.setLoginUser(true);
        }
        return blogInfo;
    }
    @RequestMapping("/add")
    public Result pulishBlog(String title, String content, HttpServletRequest request)
    {
        //从token中获取用户id
        System.out.println("获取到的User_token"+request.getHeader("user_token"));
        String token=request.getHeader("user_token");
        Integer id= JwtUtils.getUserIdFromToken(token);
        if(id<0 && id==null)
        {
            return Result.fial("用户未登录",false);
        }
        BlogInfo blogInfo=new BlogInfo();
        blogInfo.setUserId(id);
        blogInfo.setTitle(title);
        blogInfo.setContent(content);
        blogInfo.setUpvote(0);
        blogService.insertBlog(blogInfo);

        return Result.success(true);
    }
    //更新博客
    @RequestMapping("/update")
    public boolean updateBlog(Integer blogId,String title,String content)
    {
        BlogInfo blogInfo=new BlogInfo();
        blogInfo.setTitle(title);
        blogInfo.setContent(content);
        blogInfo.setId(blogId);
        //根据博客id去更新博客
        blogService.updateBlog(blogInfo);
        return true;
    }
    //删除博客
    @RequestMapping("/delete")
    public boolean deleteBlog(Integer blogId)
    {
        blogService.deleteBlog(blogId);
        return true;
    }
    @RequestMapping("upvote")
    public boolean upvoteBlog(Integer blogId)
    {
        Integer updvotes=blogService.upvote(blogId)+1;
        //通过博客id修改博客的点赞数
        blogService.upvoteBlog(updvotes,blogId);
        return true;
    }
}
